/* 
 * Enterprise Library Extensions - DI + ORM.
 * Copyright (C) 2006
 *
 * GNU General Public License
 *
 * This program is free software; you can redistribute 
 * it and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using ELE.EnterpriseLibrary.Data.Configuration;

namespace ELE.EnterpriseLibrary.Data
{
  /// <summary>
  /// Custom factory for a <see cref="ObjectStoredProcedureManager"/>
  /// </summary>
  public class ObjectStoredProcedureManagerCustomFactory : ICustomFactory
  {
    /// <summary>
    /// Creates an <see cref="ObjectStoredProcedureManager"/> from a configuration source
    /// </summary>
    /// <param name="context"></param>
    /// <param name="name"></param>
    /// <param name="configurationSource"></param>
    /// <param name="reflectionCache"></param>
    /// <returns></returns>
    public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
    {
      ObjectStoredProcedureConfigurationView view = new ObjectStoredProcedureConfigurationView(configurationSource);
      ObjectStoredProcedureManager createdObject = null;
      StoredProcedureData storedProcedureData = view.GetStoredProcedureData(name);
      if (storedProcedureData != null)
      {
        ObjectStoredProcedure storedProcedure = new ObjectStoredProcedure(name);
        storedProcedure.Name = storedProcedureData.Name;

        storedProcedure.Mappings = new List<ObjectSqlMapping>();
        foreach (MappingReferenceData mapRef in storedProcedureData.Mappings)
        {
          ObjectSqlMapping map = new ObjectSqlMapping(mapRef.ObjectId, mapRef.Name);
          if (mapRef.OverwriteBindings != null)
          {
            ObjectSqlMappingTable table = new ObjectSqlMappingTable("Overwrites");
            table.IsPrimary = true;
            map.PrimaryTableName = "Overwrites";
            foreach (PropertyBindingOverwriteData owBind in mapRef.OverwriteBindings)
            {
              ObjectPropertySqlBinding binding = new ObjectPropertySqlBinding(owBind.Name);
              binding.Ignore = owBind.Ignore;
              binding.OutputFieldName = owBind.OutName;
              binding.InputFieldName = owBind.InName;
              binding.NullableValue = owBind.NullableValue;
              binding.Direction = owBind.Direction;
              table.AddBinding(binding);
            }
            map.AddTable(table);
          }
          storedProcedure.Mappings.Add(map);
        }
        storedProcedure.Cursors = new List<ObjectStoredProcedureCursor>();
        foreach (CursorMappingData mapCursor in storedProcedureData.Cursors)
        {
          ObjectStoredProcedureCursor cursor = new ObjectStoredProcedureCursor(mapCursor.Name);
          foreach (MappingReferenceData mapRef in mapCursor.Mappings)
          {
            ObjectSqlMapping map = new ObjectSqlMapping(mapRef.ObjectId, mapRef.Name);
            if (mapRef.OverwriteBindings != null)
            {
              ObjectSqlMappingTable table = new ObjectSqlMappingTable("Overwrites");
              table.IsPrimary = true;
              map.PrimaryTableName = "Overwrites";
              foreach (PropertyBindingOverwriteData owBind in mapRef.OverwriteBindings)
              {
                ObjectPropertySqlBinding binding = new ObjectPropertySqlBinding(owBind.Name);
                binding.Ignore = owBind.Ignore;
                binding.OutputFieldName = owBind.OutName;
                binding.InputFieldName = owBind.InName;
                binding.NullableValue = owBind.NullableValue;
                binding.Direction = owBind.Direction;
                table.AddBinding(binding);
              }
              map.AddTable(table);
            }
            cursor.Mappings.Add(map);
          }
          storedProcedure.Cursors.Add(cursor);
        }
        createdObject = new ObjectStoredProcedureManager(storedProcedure);
      }

      RegisterObject(context, name, createdObject);
      return createdObject;
    }
    /// <summary>
    /// </summary>
    private void RegisterObject(IBuilderContext context, string name, ObjectStoredProcedureManager createdObject)
    {
      if (context.Locator != null)
      {
        ILifetimeContainer lifetime = context.Locator.Get<ILifetimeContainer>(typeof(ILifetimeContainer), SearchMode.Local);

        if (lifetime != null)
        {
          context.Locator.Add(new DependencyResolutionLocatorKey(typeof(ObjectStoredProcedureManager), name), createdObject);
          lifetime.Add(createdObject);
        }
      }
    }
  }

}
